package b1.scenes.home
{
	import b1.conifg.*;
	import b1.controls.basic.*;
	import b1.net.*;
	import b1.players.*;
	import b1.scenes.*;
	import b1.utils.*;
	
	import com.greensock.TweenLite;
	
	import flash.display.Sprite;
	import flash.events.*;
	import flash.filters.BitmapFilterQuality;
	import flash.filters.BitmapFilterType;
	import flash.filters.GradientGlowFilter;
	import flash.text.TextField;
	import flash.text.TextFieldAutoSize;
	import flash.text.TextFormat;
	import flash.ui.Mouse;
	import flash.utils.Timer;

	public class HomeAnimal extends Sprite
	{
		public var animalId:int;
		public var animalMessage:AnimalMessage;
		public var changeStatusTimer:Timer;
		public var mouseOverFlag:Boolean;
		private var timer:Timer;
		public var animalMc:AnimalMc;
		private var prisonCage:Sprite; 
		//毫秒
		private const updateInterval:int = 150;
		//监狱的标识符
		private var hasPrisonFlag:Boolean;
		//手铐
		private var handcuffs:Sprite;
		private var handcuffsLevel:Sprite;
		private var handcuffsShineFlag:int;
		private var handcuffsTip:BasicMessage;
		//目前所在的家的背景类型
		private var homeIndex:int;
		//技能点
		private var skillPointIcon:Sprite;
		private var skillPointIconTip:BasicMessage;
		private var skillPointIconShineFlag:int;
		private var gradientGlow:GradientGlowFilter;
		//讲话
		private var wordSprite:Sprite;
		//拖动标记
		private var dragFlag:Boolean;
		
		public function HomeAnimal(animalId:int, homeIndex:int)
		{
			super();
			var animalInfo:AnimalInfo = PlayerInfoHelper.getInstance().animals[animalId];
			this.dragFlag = false;
			var animalConfig:AnimalConfig = Config.animalConfigs[animalInfo.animalIndex];
			this.animalId = animalId;
			this.homeIndex = homeIndex;
			mouseOverFlag = false;
			handcuffsShineFlag = 0;
			animalMc = new AnimalMc(animalId, animalConfig.heightInHome);
			animalMc.status = 0;
			addChild(animalMc);
			animalMc.addEventListener(MouseEvent.MOUSE_OVER, onMouseOver);
			animalMc.addEventListener(MouseEvent.MOUSE_OUT, onMouseOut);
			//技能点图标
			skillPointIconShineFlag = 0;
			var SkillPointIcon:Class = ResourceHelper.getInstance().getClassByName("PlusImage");
			var skillPointImg:Sprite = new SkillPointIcon();
			skillPointImg.width = 20;
			skillPointImg.height = 20;
			skillPointImg.x = -skillPointImg.width / 2;
			skillPointImg.y = -skillPointImg.height / 2;
			skillPointIcon = new Sprite();
			skillPointIcon.addChild(skillPointImg);
			skillPointIcon.x = animalMc.x;
			skillPointIcon.y = animalMc.y - animalMc.animalHeight - 20;
			addChild(skillPointIcon);
			setSkillPointIconVisibility();
			skillPointIconStartShine();
			skillPointIcon.addEventListener(MouseEvent.MOUSE_OVER, skillPointIconOnMouseOver);
			//点击技能点图标效果和鼠标移动到动物身上的效果一样
			skillPointIcon.addEventListener(MouseEvent.CLICK, onMouseOver);
			skillPointIcon.addEventListener(MouseEvent.MOUSE_OUT, skillPointIconOnMouseOut);
			//动物可以被拖动
			animalMc.addEventListener(MouseEvent.MOUSE_DOWN, onMouseDown);
			animalMc.addEventListener(MouseEvent.MOUSE_UP, onMouseUp);
			//监狱
			if (animalInfo.timeToGetFree > ServerHelper.getInstance().now())
			{
				prisonCage = buildPrisonCage();
				addChild(prisonCage);
				hasPrisonFlag = true;
			}
			else
			{
				hasPrisonFlag = false;
			}
			
			//手铐
			//如果正被通缉，并且不是我自己的动物，可以直接逮捕
			if (animalInfo.wantedBones > 0 && animalInfo.timeToClose > ServerHelper.getInstance().now() && animalInfo.ownerId != PlayerInfoHelper.getInstance().userId)
			{
				var Handcuffs:Class = ResourceHelper.getInstance().getClassByName("Handcuffs");
				var handcuffs:Sprite = new Handcuffs();
				handcuffs.width = 40;
				handcuffs.height = 40;
				handcuffs.x = -handcuffs.width / 2;
				handcuffs.y = -handcuffs.height / 2;
				handcuffsLevel = new Sprite();
				handcuffsLevel.addChild(handcuffs);
				handcuffsLevel.x = animalMc.x;
				handcuffsLevel.y = animalMc.y - animalMc.animalHeight - 40;
				addChild(handcuffsLevel);
				handcuffsLevelStartShine();
				handcuffsLevel.addEventListener(MouseEvent.MOUSE_OVER, handcuffsLevelOnMouseOver);
				handcuffsLevel.addEventListener(MouseEvent.MOUSE_OUT, handcuffsLevelOnMouseOut);
				handcuffsLevel.addEventListener(MouseEvent.CLICK, arrestClick);
			}
			
			startWalk();
		}

		//开始拖动
		private function onMouseDown(event:MouseEvent):void
		{
			if (StoryHelper.getInstance().storyModeFlag)
				return;
			if (this.y != adjustPosY())
				return;
			dragFlag = true;
			if (this.animalMessage != null)
				this.animalMessage.close();
			this.stopWalk();
			this.startDrag();
		}

		//停止拖动
		private function onMouseUp(event:MouseEvent):void
		{
			if (StoryHelper.getInstance().storyModeFlag)
				return;
			this.stopDrag();
			var adjustY:int = adjustPosY();
			TweenLite.to(this, 1, {x:this.x, y:adjustY, onComplete:onAdjustYComplete});
		}

		//Y位置调整到位
		private function onAdjustYComplete():void
		{
			this.dragFlag = false;
			this.startWalk();
		}
		
		//动物讲话，开始走路
		public function reachPositionOnComplete(words:String):void
		{
			startSpeak(words);
			startWalk();
		}
		
		//讲话
		public function startSpeak(words:String):void
		{
			if (null == wordSprite)
			{
				var ClueMsgBgrImage:Class = ResourceHelper.getInstance().getClassByName("DialogMsgBgrImage");
				wordSprite = new ClueMsgBgrImage();
				var text:TextField = new TextField();
				text.selectable = false;
	        	text.autoSize = TextFieldAutoSize.CENTER;
	        	text.wordWrap = true;
	        	text.width = wordSprite.width * 0.8;
	        	text.defaultTextFormat = new TextFormat("微软雅黑", 15, 0x000000);
	        	text.text = words;
	        	text.x = 10;
	        	text.y = 10;
				wordSprite.addChild(text);
				wordSprite.x = this.x;
				wordSprite.y = this.y - this.height - wordSprite.height;
				this.parent.addChild(wordSprite);
				TweenLite.delayedCall(3, stopSpeak);
				wordSprite.mouseEnabled = false;
				wordSprite.mouseChildren = false;
			}
		}
		
		//停止讲话
		public function stopSpeak():void
		{
			if (null != wordSprite && null != wordSprite.parent)
			{
				wordSprite.parent.removeChild(wordSprite);
			}
		}
		
		//动物开始走路
		public function startWalk():void
		{
			if (null == timer)
			{
				timer = new Timer(updateInterval);
			}
			timer.start();
			timer.addEventListener(TimerEvent.TIMER, onTick);
			if (null == changeStatusTimer)
			{
				changeStatusTimer = new Timer(10000);
			}
			changeStatusTimer.start();
			changeStatusTimer.addEventListener(TimerEvent.TIMER, onChangeStatus);
		}

		//动物停止走路
		public function stopWalk():void
		{
			if (null != timer)
			{
				timer.stop();
				timer.removeEventListener(TimerEvent.TIMER, onTick);
			}
			if (null != changeStatusTimer)
			{
				changeStatusTimer.stop();
				changeStatusTimer.removeEventListener(TimerEvent.TIMER, onChangeStatus);
			}
			
		}
		
		public function refreshEquips():void
		{
			animalMc.refreshEquips();
		}
		
		private function handcuffsLevelOnMouseOver(event:MouseEvent):void
		{
			var animalInfo:AnimalInfo = PlayerInfoHelper.getInstance().animals[animalId];
			var string:String = "正被通缉中，点击逮捕";
			handcuffsTip = new BasicMessage(180, 30, string, 0x9999FF);
			Mouse.cursor = "button";
			handcuffsTip.y = animalMc.y - animalMc.animalHeight - 120;
			handcuffsTip.x = animalMc.x - handcuffsTip.width / 2
			addChild(handcuffsTip);
		}
		
		private function arrestClick(event:MouseEvent):void
		{
			var claimBones:int = Config.claimBonesForWrongIdentification;
			var detectivePlayer:PlayerInfo = PlayerInfoHelper.getInstance().players[PlayerInfoHelper.getInstance().userId];
			ServerHelper.getInstance().identifyWantedAnimal(detectivePlayer.id, animalId, claimBones, onIdentifyComplete);
		}
		
		public function onIdentifyComplete(result:String, wantedBonesSum:int, battleCases:Array):void
		{
			var rejectFlag:Boolean;
			if (result == "right")
			{
				rejectFlag = false;
			}
			else
			{
				rejectFlag = true;
			}
			var claimBones:int = Config.claimBonesForWrongIdentification;
			var detectivePlayer:PlayerInfo = PlayerInfoHelper.getInstance().players[PlayerInfoHelper.getInstance().userId];
			var detectiveAnimal:AnimalInfo = PlayerInfoHelper.getInstance().animals[detectivePlayer.ownAnimals[0]];
			var animalInfo:AnimalInfo = PlayerInfoHelper.getInstance().animals[animalId];
			var arrestDialog:ArrestWarrantDialog = new ArrestWarrantDialog(detectiveAnimal, animalInfo, rejectFlag, claimBones, 1, null, wantedBonesSum, battleCases);
			arrestDialog.x = (BFont.stageWidth - arrestDialog.width) / 2;
			arrestDialog.y = 80;
			SceneContainer.getInstance().currentScene.addChild(arrestDialog);
		}
		
		private function handcuffsLevelOnMouseOut(event:MouseEvent):void
		{
			if (null !=  handcuffsTip && null != handcuffsTip.parent)
        	{
        		Mouse.cursor = "auto";
        		handcuffsTip.parent.removeChild(handcuffsTip);
        	}
		}
		
		public function handcuffsLevelStartShine():void
		{
			var gradientGlow2:GradientGlowFilter = new GradientGlowFilter();
			gradientGlow2.distance = 0;
			gradientGlow2.angle = 45;
			gradientGlow2.colors = [0xFFFFFF, 0x9999FF];
			gradientGlow2.alphas = [0, 1];
			gradientGlow2.ratios = [0, 255];
			gradientGlow2.blurX = 10;
			gradientGlow2.blurY = 10;
			gradientGlow2.strength = 4;
			gradientGlow2.quality = BitmapFilterQuality.HIGH;
			gradientGlow2.type = BitmapFilterType.OUTER;
			handcuffsLevel.filters = [gradientGlow2];
		}
		
		public function removeHandcuffs():void
		{
			if (handcuffsLevel != null && handcuffsLevel.parent != null) 
				handcuffsLevel.parent.removeChild(handcuffsLevel);
		}
		
		private function skillPointIconOnMouseOver(event:MouseEvent):void
		{
			var animalInfo:AnimalInfo = PlayerInfoHelper.getInstance().animals[animalId];
			var string:String = "未用技能点: " + animalInfo.skillPoint.toString();
			skillPointIconTip = new BasicMessage(130, 25, string, 0xEECF1F);
			skillPointIconTip.y = animalMc.y - animalMc.animalHeight - 70;
			skillPointIconTip.x = animalMc.x - skillPointIconTip.width / 2;
			addChild(skillPointIconTip);
		}
		
		private function skillPointIconOnMouseOut(event:MouseEvent):void
		{
			if (null !=  skillPointIconTip && null != skillPointIconTip.parent)
        	{
        		skillPointIconTip.parent.removeChild(skillPointIconTip);
        	}
		}
		
		//设置技能点图标的可见性
		public function setSkillPointIconVisibility():void
		{
			var animalInfo:AnimalInfo = PlayerInfoHelper.getInstance().animals[animalId];
			if (animalInfo.skillPoint > 0 && animalInfo.ownerId == PlayerInfoHelper.getInstance().userId)
			{
				skillPointIcon.visible = true;
				animalMcStartShine();
			}
			else
			{
				skillPointIcon.visible = false;
				animalMcStopShine();
			}
		}
		
		//技能点图标的发光
		public function skillPointIconStartShine():void
		{
			gradientGlow = new GradientGlowFilter();
			gradientGlow.distance = 0;
			gradientGlow.angle = 45;
			gradientGlow.colors = [0xFFFFFF, 0xEECF1F];
			gradientGlow.alphas = [0, 1];
			gradientGlow.ratios = [0, 255];
			gradientGlow.blurX = 10;
			gradientGlow.blurY = 10;
			gradientGlow.strength = 4;
			gradientGlow.quality = BitmapFilterQuality.HIGH;
			gradientGlow.type = BitmapFilterType.OUTER;
			skillPointIcon.filters = [gradientGlow];
		}
		
		//有技能点时，动物发光
		public function animalMcStartShine():void
		{
			var gradientGlow:GradientGlowFilter = new GradientGlowFilter();
			gradientGlow.distance = 0;
			gradientGlow.angle = 45;
			gradientGlow.colors = [0xFFFFFF, 0xEECF1F];//0xFFFE65
			gradientGlow.alphas = [0, 1];
			gradientGlow.ratios = [0, 255];
			gradientGlow.blurX = 10;
			gradientGlow.blurY = 10;
			gradientGlow.strength = 2;
			gradientGlow.quality = BitmapFilterQuality.MEDIUM;
			gradientGlow.type = BitmapFilterType.OUTER;
			animalMc.filters = [gradientGlow];
		}
		
		//无技能点时，动物停止发光
		public function animalMcStopShine():void
		{
			animalMc.filters = null;
		}
		
		public function stopTimer():void
		{
			changeStatusTimer.stop();
			changeStatusTimer.removeEventListener(TimerEvent.TIMER, onChangeStatus);
		}
		
		public function removePrisonCage():void
		{
			if (this.hasPrisonFlag)
			{
				this.hasPrisonFlag = false;
				if (this.x < BFont.stageWidth / 2)
				{
					TweenLite.to(prisonCage, 1, {x:200, y:-300, scaleX:0, scaleY:0, rotation: 540, onComplete:removePrisonCageComplete});
				}
				else
				{
					TweenLite.to(prisonCage, 1, {x:-200, y:-300, scaleX:0, scaleY:0, rotation: -540, onComplete:removePrisonCageComplete});
				}
			}
		}
		
		private function removePrisonCageComplete():void
		{
			if (prisonCage != null && prisonCage.parent != null)
			{
				prisonCage.parent.removeChild(prisonCage);
				prisonCage = null;
			}
		}
		
		public function addPrisonCage():void
		{
			if (!this.hasPrisonFlag)
			{
				this.hasPrisonFlag = true;
				//监狱笼子
				var prisonCage:Sprite = buildPrisonCage();
				addChild(prisonCage);
				var fromPosX:Number = prisonCage.x;
				var fromPosY:Number = prisonCage.y - 100;
				TweenLite.from(prisonCage, 1, {x:fromPosX, y:fromPosY, scaleX:0.1, scaleY:0.1, rotation: 540, onComplete:showPrisonCageComplete, onCompleteParams:[prisonCage]});
			}
		}
		
		private function buildPrisonCage():Sprite
		{
			var PrisonCage:Class = ResourceHelper.getInstance().getClassByName("PrisonCage");
			var prisonCageImage:Sprite = new PrisonCage();
			var prisonCage:Sprite = new Sprite();
			prisonCageImage.x = -prisonCageImage.width / 2;
			prisonCageImage.y = -prisonCageImage.height / 2;
			prisonCage.addChild(prisonCageImage);
			prisonCage.mouseEnabled = false;
			prisonCage.mouseChildren = false;
			prisonCage.height = 160;
			prisonCage.width = 160;
			prisonCage.x = 0;
			prisonCage.y = -prisonCage.height / 4;
			return prisonCage;
		} 
		
		private function showPrisonCageComplete(prisonCage:Sprite):void
		{
			if (this.prisonCage != null && this.prisonCage.parent != null)
			{
				this.prisonCage.parent.removeChild(this.prisonCage);
			}
			this.prisonCage = prisonCage;
		}

		private function onMouseOver(event:MouseEvent):void
		{
			Mouse.cursor = "button";
			if (!dragFlag)
			{
				mouseOverFlag = true;
				openAnimaMessage();
			}
		}
		
		private function onMouseOut(event:MouseEvent):void
		{
			Mouse.cursor = "auto";
			mouseOverFlag = false;
		}
		
		private function openAnimaMessage():void
		{
			if (StoryHelper.getInstance().storyModeFlag || SceneContainer.getInstance().step > 0)
				return;
			if (animalMessage == null)
			{
				if (this.x > BFont.stageWidth / 2)
				{
					animalMessage = new AnimalMessage(this, 1);
					animalMessage.x = this.x - this.animalMc.animalWidth / 2;
					animalMessage.y = this.y - this.animalMc.animalHeight - animalMessage.height + 20;
				}
				else
				{
					animalMessage = new AnimalMessage(this, 0);
					animalMessage.x = this.x + this.animalMc.animalWidth / 2;
					animalMessage.y = this.y - this.animalMc.animalHeight - animalMessage.height + 20;
				}
				this.parent.addChild(animalMessage);
			}
		}
		
		private function onChangeStatus(event:Event):void
		{
			animalMc.status = Math.random() * 3;
		}
		
		//调整动物行走的高度
		public function adjustPosY():int
		{
			var adjustY:int;
			if (homeIndex == 0)
			{
				//龙的家(10, 490), (400, 530),(600,550)
				if (this.x < 400)
				{
					adjustY = 490 + (4 * x - 40) / 39;
				}
				else
				{
					adjustY = 490 + 0.1 * x;
				}
			}
			else
			{
				if (this.x < 380)
				{
					adjustY = 565 - (4 * x + 200) / 33;
				}
				else
				{
					adjustY = 515;
				}
			}
			return adjustY;
		}
		
		private function onTick(event:Event):void
		{
			var stepLength:int = 5;
			var animalInfo:AnimalInfo = PlayerInfoHelper.getInstance().animals[this.animalId];
			//控制消息显示
			if (mouseOverFlag && animalMessage != null)
			{
				animalMessage.coolDownToClose = animalMessage.coolDownToCloseMax;
			}
			//走动
			if (animalInfo.timeToGetFree < ServerHelper.getInstance().now())
			{
				if (this.hasPrisonFlag)
					this.removePrisonCage();
				if (!mouseOverFlag)
				{
					if (animalMc.status == 1 && this.x > 100)
					{
						this.x -= stepLength;
					}
					else if (animalMc.status == 2 && this.x < 600)
					{
						this.x += stepLength;
					}
					this.y = adjustPosY();
					if (handcuffs != null)
					{
						handcuffs.x = animalMc.x + 40;
						handcuffs.y = animalMc.y - 50;
					}
				}
			}
			//技能点图标闪烁
			if (skillPointIconShineFlag == 5)
			{
				skillPointIcon.scaleX = 1.5;
				skillPointIcon.scaleY = 1.5;
			}
			else if(skillPointIconShineFlag == 10)
			{
				skillPointIcon.scaleX = 1;
				skillPointIcon.scaleY = 1;
				skillPointIconShineFlag = 0;
			}
			skillPointIconShineFlag ++;
			
			//手铐图标闪烁
			if (handcuffsShineFlag == 5 && handcuffsLevel != null)
			{
				handcuffsLevel.scaleX = 1.5;
				handcuffsLevel.scaleY = 1.5;
			}
			else if(handcuffsShineFlag == 10 && handcuffsLevel != null)
			{
				handcuffsLevel.scaleX = 1;
				handcuffsLevel.scaleY = 1;
				handcuffsShineFlag = 0;
			}
			handcuffsShineFlag ++;
		}
		
	}
}